package com.kingwang.training.ooad.coffeemaker.goodway.impl;

import com.kingwang.training.ooad.coffeemaker.goodway.ContainmentVessel;
import com.kingwang.training.ooad.coffeemaker.goodway.Pollable;
import com.kingwang.training.ooad.coffeemaker.hardware.api.CoffeeMakerApi;
import com.kingwang.training.ooad.coffeemaker.hardware.api.WarmerPlateStatus;
import com.kingwang.training.ooad.coffeemaker.hardware.api.WarmerState;

/**
 * @author King
 */
public class M4ContainmentVessel extends ContainmentVessel implements Pollable {
    private CoffeeMakerApi coffeeMakerApi;

    private WarmerPlateStatus lastPotStatus;

    public M4ContainmentVessel(CoffeeMakerApi coffeeMakerApi) {
        this.coffeeMakerApi = coffeeMakerApi;
    }

    @Override
    public Boolean isReady() {
        WarmerPlateStatus status = this.coffeeMakerApi.getWarmerPlateStatus();

        return WarmerPlateStatus.POT_EMPTY.equals(status);
    }

    @Override
    public void poll() {
        WarmerPlateStatus status = this.coffeeMakerApi.getWarmerPlateStatus();

        if (!this.lastPotStatus.equals(status)) {
            if (this.brewing) {
                handleBrewingEvent(status);
            } else if (!this.completed) {
                handleIncompleteEvent(status);
            }

            this.lastPotStatus = status;
        }
    }

    private void handleBrewingEvent(WarmerPlateStatus status) {
        switch (status) {
            case POT_NOT_EMPTY:
                containerAvailable();
                this.coffeeMakerApi.setWarmerState(WarmerState.ON);
                break;
            case WARMER_EMPTY:
                containerUnavailable();
                this.coffeeMakerApi.setWarmerState(WarmerState.OFF);
                break;
            default:
                containerAvailable();
                this.coffeeMakerApi.setWarmerState(WarmerState.OFF);
                break;
        }
    }

    private void handleIncompleteEvent(WarmerPlateStatus status) {
        switch (status) {
            case POT_NOT_EMPTY:
                this.coffeeMakerApi.setWarmerState(WarmerState.ON);
                break;
            case WARMER_EMPTY:
                this.coffeeMakerApi.setWarmerState(WarmerState.OFF);
                break;
            default:
                this.coffeeMakerApi.setWarmerState(WarmerState.OFF);
                declareComplete();
                break;
        }
    }
}
